package iotwisp.school.system.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;

import iotwisp.school.system.command.SendValidSmsSCmd;
import iotwisp.base.orm.StringIdBaseEntity;
import iotwisp.base.util.RandomUtil;
import iotwisp.base.util.UUIDGenerator;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import lombok.Data;
import lombok.EqualsAndHashCode;

@SuppressWarnings("serial")
@Data
@EqualsAndHashCode(callSuper = false)
@DynamicUpdate
@DynamicInsert
@Entity
@Table(name = M.TABLE_PREFIX + "sms_valid_saga")
public class SmsValidSaga extends StringIdBaseEntity {

	/**
	 * 发送的手机号
	 */
	@Column(name = "mobile", length = 16)
	private String mobile;

	/**
	 * 业务类型
	 */
	@Column(name = "biz_type", length = 32)
	private String bizType;

	/**
	 * 验证码
	 */
	@Column(name = "valid_code", length = 8)
	private String validCode;

	/**
	 * 验证失败次数
	 */
	@Column(name = "failure_times", length = 4)
	private Integer failureTimes;

	/**
	 * 最大可验证次数
	 */
	@Column(name = "max_valid_times", length = 4)
	private Integer maxValidTimes;

	/**
	 * 状态
	 */
	@Column(name = "status")
	@Enumerated(EnumType.STRING)
	private Status status;

	/**
	 * 待验证， 成功， 失败，失效
	 * 
	 * @author yuxx
	 *
	 */
	public enum Status {
		wait, success, failure, invalid
	}

	/**
	 * 创建时间
	 */
	@Column(name = "create_date", columnDefinition = M.DATE_COLUMN)
	private Date createDate;

	/**
	 * 超时秒数
	 */
	@Column(name = "timeout_seconds", length = 8)
	private Integer timeoutSeconds;

	public void create(SendValidSmsSCmd cmd, String code) {
		
		setId(UUIDGenerator.getUUID());
		setMobile(cmd.getMobile());
		setBizType(cmd.getBizType());
		setFailureTimes(0);
		setMaxValidTimes(5);
		setTimeoutSeconds(300);
		setValidCode(code);
		setCreateDate(new Date());
		setStatus(Status.wait);

	}

	public static void main(String[] args) {
		System.out.println(RandomUtil.getNumber(0, 999999, 6));
	}

	/**
	 * 排除某些字段值后返回给app
	 * 
	 * @return
	 */
	public Object toApp() {
		setValidCode(null);
		setFailureTimes(null);
		setStatus(null);
		return this;
	}

	public boolean canValid() {
		long timeSeconds = (System.currentTimeMillis() - this.createDate.getTime()) / 1000;
		if (this.maxValidTimes > this.failureTimes && this.getTimeoutSeconds() > timeSeconds) {
			return true;
		} else {
			this.status = Status.invalid;
			return false;
		}
	}
}
